package com.xiaochen.progressroundbutton;

import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.element.PixelMapElement;
import ohos.agp.render.Canvas;
import ohos.agp.utils.Color;
import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayAttributes;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;

import ohos.global.resource.NotExistException;
import ohos.global.resource.Resource;

import ohos.multimodalinput.event.TouchEvent;

import java.io.IOException;

import java.util.Optional;

import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_PARENT;

/**
 * Created by tanfujun on 10/26/16.
 */
public class AnimButtonLayout extends DirectionalLayout implements Component.EstimateSizeListener, Component.TouchEventListener, Component.DrawTask {
    private static final long ANIM_DOWN_DURATION = 128;
    private static final long ANIM_UP_DURATION = 352;

    private AnimDownloadProgressButton mDownloadProgressButton;
    private PixelMapElement mShadowDrawable;
    private float mDensity;
    private float mCenterX;
    private float mCenterY;
    private int mLayoutWidth;
    private int mLayoutHeight;
    private float mCanvasScale = 1f;

    private float mTargetScale = 1.0f;
    private float mMinScale = 0.95f;

    public AnimButtonLayout(Context context) throws IOException, NotExistException {
        super(context);
        init(context, null);
        mDownloadProgressButton = new AnimDownloadProgressButton(context);
        DirectionalLayout.LayoutConfig layoutConfig = new DirectionalLayout.LayoutConfig(MATCH_PARENT, MATCH_PARENT);
        mDownloadProgressButton.setLayoutConfig(layoutConfig);
        this.addComponent(mDownloadProgressButton);
        // 设置TouchEvent响应事件
        setTouchEventListener(this);
        // 添加绘制任务
        addDrawTask(this);
    }

    public AnimButtonLayout(Context context, AttrSet attrs) throws IOException, NotExistException {
        super(context, attrs);
        init(context, attrs);
        mDownloadProgressButton = new AnimDownloadProgressButton(context, attrs);
        LayoutConfig layoutConfig = new LayoutConfig(MATCH_PARENT, MATCH_PARENT);
        mDownloadProgressButton.setLayoutConfig(layoutConfig);
        addComponent(mDownloadProgressButton);
        // 设置TouchEvent响应事件
        setTouchEventListener(this);
        // 添加绘制任务
        addDrawTask(this);
    }

    private void init(Context context, AttrSet attributeSet) throws IOException, NotExistException {
        Resource resource = context.getResourceManager().getResource(ResourceTable.Media_gradient_layout_shadow);
        mShadowDrawable = new PixelMapElement(resource);

        Optional<Display> defaultDisplay = DisplayManager.getInstance().getDefaultDisplay(this.getContext());
        DisplayAttributes displayAttributes = defaultDisplay.get().getAttributes();
        mDensity = displayAttributes.densityDpi;
    }

    @Override
    public void onDraw(Component component, Canvas canvas) {
        canvas.save();
        canvas.scale(mCanvasScale, mCanvasScale, mCenterX, mCenterY);
        drawShadow(canvas);
        canvas.restore();
    }

    /**
     * 画阴影
     *
     * @param canvas
     */
    private void drawShadow(Canvas canvas) {
        if (mShadowDrawable == null) {
            return;
        }
        // 绘制阴影,阴影也会根据触摸事件进行旋转
        canvas.save();
        // scale最小是为0.7f
        float scale = 1 - (1 - mCanvasScale) * 6;
        canvas.scale(scale, scale, getWidth() / 2, getHeight() / 2);
        canvas.translate(0, (mCanvasScale - 1) * getHeight() * 6 + getHeight() * 0.4f + mDensity);
        mShadowDrawable.setBounds(0, 0, getWidth(), getHeight());
        mShadowDrawable.drawToCanvas(canvas);
        canvas.restore();
    }

    @Override
    public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
        if (!isEnabled()) {
            return false;
        }
        if (!isClickable()) {
            return false;
        }

        int action = touchEvent.getAction();
        switch (action) {
            case TouchEvent.PRIMARY_POINT_DOWN:
                handleActionDown();
                break;
            case TouchEvent.PRIMARY_POINT_UP:
                handleActionUp();
                break;
            case TouchEvent.POINT_MOVE:
                break;
            case TouchEvent.CANCEL:
                break;
            default:
                break;
        }

        return true;
    }

    @Override
    public boolean onEstimateSize(int widthEstimateConfig, int heightEstimateConfig) {
        int width = Component.EstimateSpec.getSize(widthEstimateConfig);
        int height = Component.EstimateSpec.getSize(heightEstimateConfig);
        mLayoutWidth = width;
        mLayoutHeight = height;
        mCenterX = mLayoutWidth / 2;
        mCenterY = mLayoutHeight / 2;
        if (mShadowDrawable == null) {
            return false;
        }
        mShadowDrawable.setBounds(0, 0, mLayoutWidth, mLayoutHeight);

        return true;
    }

    /**
     * 处理ActionDown事件
     */
    private void handleActionDown() {
        isDraw();
        setupLayoutDownAnimator();
    }

    /**
     * 处理handleActionUp事件
     */
    private void handleActionUp() {
        setDraw();
        setupLayoutUpAnimator();
    }

    /**
     * 点下去的动画
     */
    private void setupLayoutDownAnimator() {
        setScale(1, 1);
        AnimatorProperty animator = createAnimatorProperty();
        animator.setCurveType(Animator.CurveType.ACCELERATE_DECELERATE);
        animator.scaleY(mMinScale);
        animator.scaleX(mMinScale);
        animator.setDuration(ANIM_DOWN_DURATION);
        animator.start();
        invalidate();
    }

    /**
     * 抬起手来的动画
     */
    private void setupLayoutUpAnimator() {
        setScale(1, 1);
        AnimatorProperty animator = createAnimatorProperty();
        animator.setCurveType(Animator.CurveType.ACCELERATE_DECELERATE);
        animator.scaleY(mTargetScale);
        animator.scaleX(mTargetScale);
        animator.setDuration(ANIM_UP_DURATION);
        animator.start();
        invalidate();
    }

    @Override
    public void invalidate() {
        super.invalidate();
        mDownloadProgressButton.invalidate();
    }

    private void isDraw() {
        mDownloadProgressButton.isDraw();
    }

    private void setDraw() {
        mDownloadProgressButton.setDraw();
    }

    /**
     * 获取按钮当前进行状态
     *
     * @return int
     */
    public int getState() {
        return mDownloadProgressButton.getState();
    }

    /**
     * 设置按钮当前进行状态
     *
     * @param state 状态值
     */
    public void setState(int state) {
        mDownloadProgressButton.setState(state);
    }

    /**
     * 设置按钮文字
     *
     * @param charSequence 文本对象
     */
    public void setCurrentText(CharSequence charSequence) {
        mDownloadProgressButton.setCurrentText(charSequence);
    }

    /**
     * 设置带下载进度的文字
     *
     * @param text     文本
     * @param progress 进度值
     */
    public void setProgressText(String text, float progress) {
        mDownloadProgressButton.setProgressText(text, progress);
    }

    /**
     * 获取按钮当前进度值
     *
     * @return 进度值
     */
    public float getProgress() {
        return mDownloadProgressButton.getProgress();
    }

    /**
     * 设置按钮当前进度值
     *
     * @param progress 进度值
     */
    public void setProgress(float progress) {
        mDownloadProgressButton.setProgress(progress);
    }

    /**
     * Sometimes you should use the method to avoid memory leak
     */
    public void removeAllAnim() {
        mDownloadProgressButton.removeAllAnim();
    }

    /**
     * 获取按钮圆角
     *
     * @return 圆角值
     */
    public float getButtonRadius() {
        return mDownloadProgressButton.getButtonRadius();
    }

    /**
     * 设置按钮圆角
     *
     * @param buttonRadius 圆角值
     */
    public void setButtonRadius(float buttonRadius) {
        mDownloadProgressButton.setButtonRadius(buttonRadius);
    }

    /**
     * 获取按钮文字颜色
     *
     * @return 颜色色值
     */
    public int getTextColor() {
        return mDownloadProgressButton.getTextColor().getValue();
    }

    /**
     * 设置文字颜色
     *
     * @param textColor 颜色色值
     */
    public void setTextColor(int textColor) {
        mDownloadProgressButton.setTextColor(new Color(textColor));
    }

    /**
     * 获取文字转变色
     *
     * @return 颜色色值
     */
    public int getTextCoverColor() {
        return mDownloadProgressButton.getTextCoverColor();
    }

    /**
     * 色值文字转变色
     *
     * @param textCoverColor 颜色色值
     */
    public void setTextCoverColor(int textCoverColor) {
        mDownloadProgressButton.setTextCoverColor(textCoverColor);
    }

    /**
     * 获取最小进度值
     *
     * @return 进度值
     */
    public int getMinProgress() {
        return mDownloadProgressButton.getMinProgress();
    }

    /**
     * 设置最小进度值
     *
     * @param minProgress 进度值
     */
    public void setMinProgress(int minProgress) {
        mDownloadProgressButton.setMinProgress(minProgress);
    }

    /**
     * 获取最大进度值
     *
     * @return 进度值
     */
    public int getMaxProgress() {
        return mDownloadProgressButton.getMaxProgress();
    }

    /**
     * 设置最大进度值
     *
     * @param maxProgress 进度值
     */
    public void setMaxProgress(int maxProgress) {
        mDownloadProgressButton.setMaxProgress(maxProgress);
    }

    /**
     * 是否设置默认按下
     *
     * @param enable 是否
     */
    public void enabelDefaultPress(boolean enable) {
        mDownloadProgressButton.enabelDefaultPress(enable);
    }

    /**
     * 是否设置默认渐变色
     *
     * @param enable 是否
     */
    public void enabelDefaultGradient(boolean enable) {
        mDownloadProgressButton.enabelDefaultGradient(enable);
    }

    /**
     * 设置文字大小
     *
     * @param size 文字大小
     */
    public void setTextSize(int size) {
        mDownloadProgressButton.setTextSize(size);
    }

    /**
     * 获取文字大小
     *
     * @return 文字大小
     */
    public float getTextSize() {
        return mDownloadProgressButton.getTextSize();
    }

    /**
     * 设置自定义控制器
     *
     * @param customerController 自定义控制器
     * @return AnimDownloadProgressButton
     */
    public AnimDownloadProgressButton setCustomerController(ButtonController customerController) {
        return mDownloadProgressButton.setCustomerController(customerController);
    }

}
